package com.kjs.common.tools;

import java.util.Locale;
import java.util.Random;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 字符串的各种变换支持
 * @author wujr
 *
 */
public class StringCodec {
	private final static char[] mChars = "0123456789ABCDEF".toCharArray();
	private static final String sAlpha = "abcdefghigklmnopkrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789";
	private static final String sDigits = "0123456789";
	
	/**
	 * 字符串中的空格、回车、换行符、制表符
	 * 注：\n 回车(\u000a) 
    \t 水平制表符(\u0009) 
    \s 空格(\u0008) 
    \r 换行(\u000d)
	 * @param str
	 * @return
	 */
	public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
	
	/**
	 * 转换为16进制字符串
	 * @param src
	 * @return
	 */
	public static String bin2hex(byte[] src){
		StringBuffer hexValue = new StringBuffer(src.length * 2);
        for (int i = 0; i < src.length; i++) {
            int val = ((int) src[i]) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        String c = hexValue.toString();
        return c;
	}
	public static String byte2hex(byte b[]){
		int iLen = b.length;
		StringBuilder sb = new StringBuilder();
        for (int n = 0; n < iLen; ++ n){
            sb.append(mChars[(b[n] & 0xFF) >> 4]);
            sb.append(mChars[b[n] & 0x0F]);
        }
        return sb.toString().trim().toUpperCase(Locale.US);
	}
	
	public static byte[] hex2byte(String h){
		//处理值初始化  
        int m=0,n=0;  
        int iLen = h.length()/2; //计算长度
        byte[] ret = new byte[iLen]; //分配存储空间
          
        for (int i = 0; i < iLen; i++){  
            m=i*2+1;  
            n=m+1;  
            ret[i] = (byte)(Integer.decode("0x"+ h.substring(i*2, m) + h.substring(m,n)) & 0xFF);  
        }  
        return ret;
	}
	public static String generate(String base, int length){
		Random random = new Random();
		char buf[] = new char[length];
		for (int i = 0; i < length; ++ i){
			int num = random.nextInt(base.length());
			buf[i] = base.charAt(num);
		}
		return new String(buf);
	}
	/**
	 * 产生字符随机字符串
	 * @param length
	 * @return
	 */
	public static String generateAlpha(int length){
		return generate(sAlpha, length);
	}
	/**
	 * 产生数字随机字符串
	 * @param length
	 * @return
	 */
	public static String generateDigit(int length){
		return generate(sDigits, length);
	}

	/**
	 * 创建32的小写uuid，没有中间的减号
	 * @return uuid字符串
	 */
	public static String uuid(){
		return UUID.randomUUID().toString().replace("-", "");
	}
}
